const puppeteer = require('puppeteer')
const fs = require('fs')

const _key = ['骨窟寺', '明洞天主教堂', '埃菲尔铁塔', '长城', '悬空寺', '布达拉宫']


async function main(item, index) {
  const browser = await puppeteer.launch({headless: false})
  const page = await browser.newPage()
  await page.goto('https://baike.baidu.com/')
  
  await page.type('#query', item, {delay: 200})
  await page.click('#search')
  await page.waitForNavigation()

  const result = await page.evaluate(() => {
    let _obj = {},
          i = 0
      _obj.title = document.querySelector('.lemmaWgt-lemmaTitle-title h1').innerText
      
      let elements = document.querySelectorAll('body > div.body-wrapper > div.content-wrapper > div > div.main-content > div.para')
      for (var ele of elements){
          i++
          if (i == 1) {
              _obj.des1 = ele.innerText.replace(/\n|\r|\t/g,"")
          }else{
              _obj.des2 += ele.innerText.replace(/\n|\r|\t/g,"")
          }
      }
      return _obj
  })


  browser.close()

  let _res = ''
  if (index == 0) {
    _res = '[' + JSON.stringify(result) + ','
  }else if (index == (_key.length - 1) ){
    _res = JSON.stringify(result) + ']'
  }else{
    _res = JSON.stringify(result) + ','
  }
  fs.writeFile( './json/3.json', _res, { flag: 'a' }, err => {
      if (err) throw err
  })
}


_key.forEach((item, index) => {
  let _time = (index + 1) * 3500
  
  setTimeout(() => {
    console.log('第' + index + '次执行')
    main(item, index)
  }, _time)
})
